<!--
 * @Author: weikang
 * @Description:
 * @Date: 2024-01-21 16:52:27
 * @LastEditTime: 2024-03-10 18:21:18
 * @FilePath: \env-manager-pc\src\views\data_query\ent_day_power\components\lineChart.vue
-->
<script setup lang="ts">
import * as Echarts from 'echarts'

const props = defineProps({
  tableData: {
    type: Array,
    default: () => ([]),
  },
})

let chart: any = null
// const series = ref<any>([])
const timeLine = computed(() => {
  return props.tableData.map((item: any) => item[1])
})
const chartRef = ref<any>()

onMounted(() => {
  chart = Echarts.init(chartRef.value)
  window.addEventListener('resize', () => {
    chart.resize()
  })
})

function getOption() {
  // 判断 x 轴的条目数量是否超过 15
  const showDataZoom = timeLine.value.length > 15
  const timeData: string[] = []
  const yData: number[] = []

  // 计算平均值
  let averageValue = 0
  let dayNum = 0
  props.tableData.forEach((item: any) => {
    timeData.push(item[1])
    yData.push(item[0])
    if (item[0] === null) {
      return
    }
    averageValue += (item[0])
    dayNum += 1
  })
  averageValue = averageValue / dayNum

  // ECharts 配置项
  const option = {
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: timeLine.value,
    },
    tooltip: {
      trigger: 'axis',
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: 50,
      top: 50,
      containLabel: true,
    },
    yAxis: {
      type: 'value',
      name: '用电量（kWh）',
      scale: true,
    },
    series: [{
      name: '用电量',
      type: 'line',
      data: yData,
      smooth: true,
      // symbol: 'none',
      lineStyle: {
        width: 1,
      },
      markLine: {
        lineStyle: {
          color: '#E6A23C', // 标线颜色
          type: 'dashed', // 设置为虚线
        },
        label: {
          position: 'middle',
          formatter: (params: any) => {
            return `平均用电${params.value}`
          },
        },
        data: [
          {
            yAxis: averageValue,
          },
        ],
      },
    }],
    dataZoom: showDataZoom
      ? [
          {
            type: 'slider', // 滑动条形式的 dataZoom
          },
        ]
      : [], // 如果不需要 dataZoom，设置为空数组
  }
  return option
}

onMounted(() => {
  chart = Echarts.init(chartRef.value)
  calcHeight()
  window.addEventListener('resize', () => {
    calcHeight()
  })
})

function calcHeight() {
  nextTick(() => {
    const footHeight = 10
    const top = chartRef.value.getBoundingClientRect().top
    const windowHeight = window.innerHeight
    const companyHeight = 50
    const height = windowHeight - top - footHeight - companyHeight
    chartRef.value.style.height = `${height}px`
    chart.resize()
  })
}

function refresh() {
  chart.setOption(getOption())
}

defineExpose({
  refresh,
})
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 100%;" />
</template>
